package com.simplemobiletools.camera

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Matrix
import android.os.Bundle
import android.os.Environment
import android.os.StatFs
import android.text.format.Formatter.formatFileSize
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.app.module.camera.ui.Camera2Activity
import com.atom.module.document.Document
import com.atom.module.document.helper.DocumentHelper
import com.atom.module.document.ui.CameraViewActivity
import com.atom.module.document.ui.DocumentListActivity
import com.atom.module.document.ui.MoreHandleActivity
import com.atom.module.document.ui.SingleHandleActivity
import com.atom.module.draw.activities.DrawActivity
import com.atom.module.face.ui.CameraActivity
import com.atom.module.logger.Logger
import com.atom.module.permissions.AutoPermissions
import com.atom.module.permissions.AutoPermissionsCallback
import com.simplemobiletools.camera.document.DocumentActivity
import com.simplemobiletools.camera.filter.AndroidGpuImagePlusActivity
import com.simplemobiletools.camera.filter.ModuleFilterActivity
import com.simplemobiletools.camera.gpuimage.GalleryActivity
import com.simplemobiletools.camera.gpuimage.GpuCameraActivity
import com.simplemobiletools.camera.utils.FileUtil
import com.simplemobiletools.camera.voucher.VoucherCameraActivity
import com.simplemobiletools.commons.extensions.toast
import java.io.File
import java.io.IOException

class LaunchActivity : AppCompatActivity() {

    @SuppressLint("MissingSuperCall")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_launch)

        findViewById<View>(R.id.to_draw).setOnClickListener {
            AutoPermissions.loadSelectedPermission(this,
                1025,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                object : AutoPermissionsCallback {
                    override fun onDenied(requestCode: Int, permissions: Array<String>) {
                        toast(R.string.no_storage_permissions)
                        finish()
                    }

                    override fun onGranted(requestCode: Int, permissions: Array<String>) {
                        if (requestCode != 1025) return
                        if (permissions.size != 1) return
                        startActivity(Intent(this@LaunchActivity, DrawActivity::class.java))
                    }
                })
        }

        findViewById<View>(R.id.to_test).setOnClickListener {
            // 获得一个磁盘状态对象
            var stat = StatFs(Environment.getDataDirectory().getPath());
            var blockSize = stat.blockSize; // 获得一个扇区的大小
            var totalBlocks = stat.blockCount.toLong(); // 获得扇区的总数
            var availableBlocks = stat.availableBlocks.toLong(); // 获得可用的扇区数量
            // 总空间
            var totalMemory = formatFileSize(this, totalBlocks * blockSize);
            // 可用空间
            var availableMemory = formatFileSize(this, availableBlocks * blockSize);
            Logger.e("总空间:(${(totalBlocks * blockSize) / 1000 / 1000 / 1000}) " + totalMemory + "\n可用空间:(${(availableBlocks * blockSize) / 1000 / 1000 / 1000}) " + availableMemory)
        }

        findViewById<View>(R.id.to_document_single_handle).setOnClickListener {
//            val intent = Intent(Intent.ACTION_PICK, null)
//            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
//            startActivityForResult(
//                intent,
//                2048
//            )

            // TODO
            val result = Intent()
            val documentSourcePath = DocumentHelper.getDocumentSourcePath(this, null);
            val sourceFolder = File(documentSourcePath)
            Document.clearDocument()
            Document.getDocument().addAll(sourceFolder.listFiles().map {
                Document.Entry.defaultEntry(it.absolutePath)
            })
            if (!Document.isEmptyDocument()) {
                result.putExtra(
                    DocumentHelper.camera_result_value_param,
                    Document.getDocument()[0].sourcePath
                )
                result.setClass(this@LaunchActivity, SingleHandleActivity::class.java)
                startActivity(result)
            }
        }
        findViewById<View>(R.id.to_document_more_handle).setOnClickListener {
            val result = Intent()
            val documentSourcePath = DocumentHelper.getDocumentSourcePath(this, null);
            val sourceFolder = File(documentSourcePath)
            Document.clearDocument()
            Document.getDocument().addAll(sourceFolder.listFiles().map {
                Document.Entry.defaultEntry(it.absolutePath)
            })
            if (!Document.isEmptyDocument()) {
                result.setClass(this@LaunchActivity, MoreHandleActivity::class.java)
                startActivity(result)
            }
        }
        findViewById<View>(R.id.to_document_list).setOnClickListener {
            val result = Intent()
            result.setClass(this@LaunchActivity, DocumentListActivity::class.java)
            startActivity(result)
        }
        findViewById<View>(R.id.to_document_camera).setOnClickListener {

            AutoPermissions.loadSelectedPermissions(this, 1024, arrayOf(
                Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA
            ), object : AutoPermissionsCallback {
                override fun onDenied(requestCode: Int, permissions: Array<String>) {
                    toast(R.string.no_storage_permissions)
                    finish()
                }

                override fun onGranted(requestCode: Int, permissions: Array<String>) {
                    if (requestCode != 1024) return
                    if (permissions.size != 2) return
                    startActivity(Intent(this@LaunchActivity, CameraViewActivity::class.java))
                }
            })
        }

        findViewById<View>(R.id.to_matrix).setOnClickListener {
            val mat = Matrix()
            //mat.setScale(0.5f, 0.5f)
            mat.setRotate(-90f)
            val src = FloatArray(2).apply {
                this[0] = -1f
                this[1] = 0f
            }
            val result = FloatArray(2)
            mat.mapPoints(result, src)
            Log.e("LaunchActivity", "${src[0]},${src[1]} -> ${result[0]},${result[1]}")
        }

        findViewById<View>(R.id.to_gpu_image_pick_file).setOnClickListener {
            startActivity(Intent(this, GalleryActivity::class.java))
        }

        findViewById<View>(R.id.to_gpu_image_open_camera).setOnClickListener {
            startActivity(Intent(this, GpuCameraActivity::class.java))
        }

        findViewById<View>(R.id.to_module_camera).setOnClickListener {
            startActivityForResult(Intent(this, CameraActivity::class.java).apply {
                //this.action = CameraActivity.ACTION_VIDEO
                //this.putExtra(CameraActivity.EXTRA_OUTPUT , Uri.fromFile(File(this@MainActivity.cacheDir , "test.mp4")))
            }, 777)
        }

        findViewById<View>(R.id.to_module_filter_camera).setOnClickListener {
            startActivityForResult(Intent(this, CameraActivity::class.java).apply {
                this.action = CameraActivity.ACTION_IMAGE
                this.putExtra(CameraActivity.STATE_SINGLE, true)
                this.putExtra(CameraActivity.AUTO_IMAGE_CAPTURE, false)
                this.putExtra(CameraActivity.AUTO_IMAGE_FACE, true)
                this.putExtra(CameraActivity.AUTO_IMAGE_TIME, 3)
            }, 777)
        }

        findViewById<View>(R.id.to_module_face_camera).setOnClickListener {
            startActivity(Intent(this, Camera2Activity::class.java))
        }
        findViewById<View>(R.id.to_voucher_camera).setOnClickListener {
            startActivity(Intent(this, VoucherCameraActivity::class.java))
        }

        findViewById<View>(R.id.to_module_filter).setOnClickListener {
            startActivity(Intent(this, ModuleFilterActivity::class.java))
        }
        findViewById<View>(R.id.to_module_filter_gpu).setOnClickListener {
            startActivity(Intent(this, AndroidGpuImagePlusActivity::class.java))
        }
        findViewById<View>(R.id.to_module_document).setOnClickListener {
            startActivity(Intent(this, DocumentActivity::class.java))
        }

        findViewById<View>(R.id.root_layout).post {
            findViewById<View>(R.id.to_module_filter_gpu).callOnClick()
            //findViewById<View>(R.id.to_camera_view).callOnClick()
            //findViewById<View>(R.id.to_document_more).callOnClick()
            //findViewById<View>(R.id.to_module_face_camera).callOnClick()
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.e("MainActivity", "$requestCode  $resultCode  ${data?.data.toString()}")
        if (requestCode == 2048 && resultCode == RESULT_OK) {
            data ?: return
            val imageUri = data.data
            try {
                if (imageUri != null) {
                    val realPathFromURI = FileUtil.getFilePathByUri(this, imageUri)
                    val result = Intent()
                    result.setClass(this@LaunchActivity, SingleHandleActivity::class.java)
                    result.putExtra(DocumentHelper.camera_result_value_param, realPathFromURI)
                    startActivity(result)
                }
            } catch (e: IOException) {
                Logger.e(e)
            }
        } else if (resultCode == RESULT_FIRST_USER) {
            Logger.e("%s", data.toString())
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        AutoPermissions.parsePermissions(this, requestCode, permissions)
    }

}
